/*
 * Copyright 2002-2018 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package gagak.framework.web.paramresovler.converter;

import gagak.framework.web.exception.HttpMessageNotReadableException;
import gagak.framework.web.exception.HttpMessageNotWritableException;
import gagak.framework.web.paramresovler.requestbody.*;
import gagak.framework.web.support.http.HttpHeaders;
import gagak.framework.web.support.http.MediaType;
import gagak.framework.web.annonation.Nullable;
import gagak.framework.web.utils.Assert;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;


/*
 *
 */
public abstract class AbstractHttpMessageConverter<T> implements HttpMessageConverter<T> {

    /*
     * Logger available to subclasses
     */
    protected final Log logger = LogFactory.getLog(getClass());


    // 它主要内部维护了这两个属性，可议构造器赋值，也可以set方法赋值~~
    private List<MediaType> supportedMediaTypes = Collections.emptyList();

    @Nullable
    private Charset defaultCharset;


    protected AbstractHttpMessageConverter() {
    }


    protected AbstractHttpMessageConverter(MediaType supportedMediaType) {
        setSupportedMediaTypes(Collections.singletonList(supportedMediaType));
    }


    protected AbstractHttpMessageConverter(MediaType... supportedMediaTypes) {
        setSupportedMediaTypes(Arrays.asList(supportedMediaTypes));
    }


    protected AbstractHttpMessageConverter(Charset defaultCharset, MediaType... supportedMediaTypes) {
        this.defaultCharset = defaultCharset;
        setSupportedMediaTypes(Arrays.asList(supportedMediaTypes));
    }


    /*
     * Set the list of {@link MediaType} objects supported by this converter.
     */
    public void setSupportedMediaTypes(List<MediaType> supportedMediaTypes) {
        Assert.notEmpty(supportedMediaTypes, "MediaType List must not be empty");
        this.supportedMediaTypes = new ArrayList<MediaType>(supportedMediaTypes);
    }

    @Override
    public List<MediaType> getSupportedMediaTypes() {
        return Collections.unmodifiableList(this.supportedMediaTypes);
    }

    /*
     * Set the default character set, if any.
     *
     * @since 4.3
     */
    public void setDefaultCharset(@Nullable Charset defaultCharset) {
        this.defaultCharset = defaultCharset;
    }

    /*
     * Return the default character set, if any.
     *
     * @since 4.3
     */
    @Nullable
    public Charset getDefaultCharset() {
        return this.defaultCharset;
    }


    // 而canRead(mediaType)表示MediaType也得在我支持的范畴了才行（入参MediaType若没有指定，就返回true的）
    @Override
    public boolean canRead(Class<?> clazz, @Nullable MediaType mediaType) {
        return supports(clazz) && canRead(mediaType);
    }


    protected boolean canRead(@Nullable MediaType mediaType) {
        if (mediaType == null) {
            return true;
        }
        for (MediaType supportedMediaType : getSupportedMediaTypes()) {
            if (supportedMediaType.includes(mediaType)) {
                return true;
            }
        }
        return false;
    }


    // 原理基本同上，supports和上面是同一个抽象方法  所以我们发现并不能入参处理Map，出餐处理List等等
    @Override
    public boolean canWrite(Class<?> clazz, @Nullable MediaType mediaType) {
        return supports(clazz) && canWrite(mediaType);
    }


    protected boolean canWrite(@Nullable MediaType mediaType) {
        if (mediaType == null || MediaType.ALL.equals(mediaType)) {
            return true;
        }
        for (MediaType supportedMediaType : getSupportedMediaTypes()) {
            if (supportedMediaType.isCompatibleWith(mediaType)) {
                return true;
            }
        }
        return false;
    }


    @Override
    public final T read(Class<? extends T> clazz, HttpInputMessage inputMessage)
            throws IOException, HttpMessageNotReadableException {

        return readInternal(clazz, inputMessage);
    }

    // 整体上就write方法做了一些事~~
    @Override
    public final void write(final T t, @Nullable MediaType contentType, HttpOutputMessage outputMessage)
            throws IOException, HttpMessageNotWritableException {

        final HttpHeaders headers = outputMessage.getHeaders();
        // 设置一个headers.setContentType 和 headers.setContentLength
        addDefaultHeaders(headers, t, contentType);

        if (outputMessage instanceof StreamingHttpOutputMessage) {
            StreamingHttpOutputMessage streamingOutputMessage = (StreamingHttpOutputMessage) outputMessage;
            // StreamingHttpOutputMessage增加的setBody()方法，关于它下面会给一个使用案例~~~~
            streamingOutputMessage.setBody(new StreamingHttpOutputMessage.Body() {
                @Override
                public void writeTo(final OutputStream outputStream) throws IOException {
                    AbstractHttpMessageConverter.this.writeInternal(t, new HttpOutputMessage() {
                        // 注意此处复写：返回的是outputStream ，它也是靠我们的writeInternal对它进行写入的~~~~
                        @Override
                        public OutputStream getBody() {
                            return outputStream;
                        }

                        @Override
                        public HttpHeaders getHeaders() {
                            return headers;
                        }
                    });
                }
            });
        }
        // 最后它执行了flush，这也就是为何我们自己一般不需要flush的原因
        else {
            writeInternal(t, outputMessage);
            outputMessage.getBody().flush();
        }
    }


    protected void addDefaultHeaders(HttpHeaders headers, T t, @Nullable MediaType contentType) throws IOException {
        if (headers.getContentType() == null) {
            MediaType contentTypeToUse = contentType;
            if (contentType == null || contentType.isWildcardType() || contentType.isWildcardSubtype()) {
                contentTypeToUse = getDefaultContentType(t);
            } else if (MediaType.APPLICATION_OCTET_STREAM.equals(contentType)) {
                MediaType mediaType = getDefaultContentType(t);
                contentTypeToUse = (mediaType != null ? mediaType : contentTypeToUse);
            }
            if (contentTypeToUse != null) {
                if (contentTypeToUse.getCharset() == null) {
                    Charset defaultCharset = getDefaultCharset();
                    if (defaultCharset != null) {
                        contentTypeToUse = new MediaType(contentTypeToUse, null);
                    }
                }
                headers.setContentType(contentTypeToUse);
            }
        }
        if (headers.getContentLength() < 0 && !headers.containsKey(HttpHeaders.TRANSFER_ENCODING)) {
            Long contentLength = getContentLength(t, headers.getContentType());
            if (contentLength != null) {
                headers.setContentLength(contentLength);
            }
        }
    }


    @Nullable
    protected MediaType getDefaultContentType(T t) throws IOException {
        List<MediaType> mediaTypes = getSupportedMediaTypes();
        return (!mediaTypes.isEmpty() ? mediaTypes.get(0) : null);
    }

    @Nullable
    protected Long getContentLength(T t, @Nullable MediaType contentType) throws IOException {
        return null;
    }


    // supports是个抽象方法，交给子类自己去决定自己支持的转换类型~~~~
    protected abstract boolean supports(Class<?> clazz);


    protected abstract T readInternal(Class<? extends T> clazz, HttpInputMessage inputMessage)
            throws IOException, HttpMessageNotReadableException;


    protected abstract void writeInternal(T t, HttpOutputMessage outputMessage)
            throws IOException, HttpMessageNotWritableException;

}
